intro to ASM: l11 bitwise logic

Using only the following instructions:
and, or, xor

Implement the following logic:
if x is even then
y = 1
else
y = 0

where:
x = rdi
y = rax

We will now set the following in preparation for your code:
rdi = 0x9efb556

SOL:

ngl, this took me a while since jump conditions were not allowed here.

before anything, we make rax 0

xor rax, rax

so we can break this problem into parts,

part 1 → determine if x % 2 = 0 or1.

if you refer to the sizes to modulo writeup,

If we have "x % y", and y is a power of 2, such as 2^n, the result will be the lower n bits of x.

so therefore, we only need the lowest most bit present in x i.e rdi

for that we do

add rdi, 1

now rdi is 0 if rdi is even, or, 1 if rdi is odd.

part 2 → set value of y to 1 or 0 based on x, case rdi = 0

if we perform

or rax, rdi 

rax is 0 always, so if rdi = 1, rax becomes 1. now this is opposite to what we want as a value of rax. we want rax to become 1 when rdi = 0 .

part 3 → not (rax)

here if u see, if we xor any value with 1, it becomes not. therefore

xor rax, 1

putting it all together,

xor rax, rax
add rdi, 1
or rax, rdi
xor rax, 1